'use client';

import { useState, useEffect } from 'react';
import { useApp } from '@/contexts/AppContext';
import { useToast } from '@/components/Toast';
import { signInRewards, lotteryPrizes } from '@/lib/mockData';
import { LotteryPrize, LotteryResult } from '@/lib/types';

export default function SignInPage() {
  const { state, dispatch } = useApp();
  const { showToast, ToastContainer } = useToast();
  
  // 防止hydration错误
  const [mounted, setMounted] = useState(false);
  
  // 签到相关状态
  const [isSigningIn, setIsSigningIn] = useState(false);
  const [currentMonth, setCurrentMonth] = useState(new Date());
  
  // 抽奖相关状态
  const [isDrawing, setIsDrawing] = useState(false);
  const [selectedPrize, setSelectedPrize] = useState<LotteryPrize | null>(null);
  const [showResult, setShowResult] = useState(false);

  useEffect(() => {
    setMounted(true);
  }, []);

  // 生成日历数据
  const generateCalendar = () => {
    const year = currentMonth.getFullYear();
    const month = currentMonth.getMonth();
    const firstDay = new Date(year, month, 1);
    const lastDay = new Date(year, month + 1, 0);
    const daysInMonth = lastDay.getDate();
    const startingDayOfWeek = firstDay.getDay();
    
    const days = [];
    
    // 添加空白天数
    for (let i = 0; i < startingDayOfWeek; i++) {
      days.push(null);
    }
    
    // 添加月份中的天数
    for (let day = 1; day <= daysInMonth; day++) {
      const date = new Date(year, month, day);
      const dateString = date.toISOString().split('T')[0];
      const today = new Date().toISOString().split('T')[0];
      const isToday = dateString === today;
      const isPast = date < new Date(today);
      
      // 模拟签到状态：过去的日期部分已签到，今天根据实际状态
      const isSignedIn = mounted ? (isToday ? state.todaySignedIn : (isPast && day % 3 !== 0)) : false;
      
      days.push({
        day,
        date: dateString,
        isToday,
        isPast,
        isSignedIn,
        canMakeUp: isPast && !isSignedIn
      });
    }
    
    return days;
  };

  // 签到处理
  const handleSignIn = async () => {
    if (isSigningIn || (mounted && state.todaySignedIn)) return;
    
    setIsSigningIn(true);
    
    setTimeout(() => {
      const consecutiveDays = state.signInRecord?.consecutiveDays || 0;
      const nextDay = (consecutiveDays % 7) + 1;
      const reward = signInRewards.find(r => r.day === nextDay);
      
      if (reward) {
        const lotteryChances = reward.type === 'lottery_chance' ? reward.value : 0;
        
        dispatch({
          type: 'SIGN_IN',
          payload: {
            reward: reward.description,
            lotteryChances
          }
        });
        
        showToast(`签到成功！${reward.description}`, 'success');
      }
      
      setIsSigningIn(false);
    }, 1000);
  };

  // 抽奖处理
  const handleLottery = async () => {
    if (!mounted || state.lotteryChances <= 0 || isDrawing) return;
    
    setIsDrawing(true);
    setShowResult(false);
    setSelectedPrize(null);
    
    // 使用抽奖机会
    dispatch({ type: 'USE_LOTTERY_CHANCE' });
    
    // 随机选择奖品
    const random = Math.random();
    let currentProbability = 0;
    let winner: LotteryPrize | null = null;
    
    for (let i = 0; i < lotteryPrizes.length; i++) {
      currentProbability += lotteryPrizes[i].probability;
      if (random <= currentProbability) {
        winner = lotteryPrizes[i];
        break;
      }
    }
    
    // 等待动画完成
    setTimeout(() => {
      if (winner) {
        const result: LotteryResult = {
          id: `LTR_${Date.now()}`,
          userId: state.user?.id || '1',
          prizeId: winner.id,
          prizeName: winner.name,
          prizeType: winner.type,
          prizeValue: winner.value,
          createdAt: new Date().toISOString(),
          claimed: false
        };
        
        dispatch({ type: 'ADD_LOTTERY_RESULT', payload: result });
        setSelectedPrize(winner);
        setShowResult(true);
        showToast(`恭喜获得：${winner.name}！`, 'success');
      }
      
      setIsDrawing(false);
    }, 2000);
  };

  const getSignInRewardPreview = () => {
    if (!mounted) return null;
    const consecutiveDays = state.signInRecord?.consecutiveDays || 0;
    const nextDay = (consecutiveDays % 7) + 1;
    return signInRewards.find(r => r.day === nextDay);
  };

  const calendarDays = generateCalendar();
  const nextReward = getSignInRewardPreview();

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <div className="max-w-7xl mx-auto px-4">
        {/* 页面标题 */}
        <div className="text-center mb-8">
          <h1 className="text-3xl font-bold text-gray-800 mb-2">每日签到</h1>
          <p className="text-gray-600">坚持签到，获取更多惊喜奖励</p>
        </div>

        <div className="grid lg:grid-cols-2 gap-8">
          {/* 左侧：签到功能 */}
          <div className="bg-white rounded-lg p-6 shadow-sm">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-xl font-bold text-gray-800">签到日历</h2>
              <div className="text-sm text-gray-600">
                {currentMonth.getFullYear()}年{currentMonth.getMonth() + 1}月
              </div>
            </div>

            {/* 统计信息 */}
            <div className="grid grid-cols-2 gap-4 mb-6">
              <div className="bg-gradient-to-r from-yellow-100 to-orange-100 p-4 rounded-lg">
                <div className="text-2xl font-bold text-orange-600">
                  {mounted ? (state.signInRecord?.consecutiveDays || 0) : 0}
                </div>
                <div className="text-sm text-gray-600">连续签到天数</div>
              </div>
              <div className="bg-gradient-to-r from-blue-100 to-purple-100 p-4 rounded-lg">
                <div className="text-2xl font-bold text-purple-600">
                  {mounted ? (state.signInRecord?.totalDays || 0) : 0}
                </div>
                <div className="text-sm text-gray-600">累计签到天数</div>
              </div>
            </div>

            {/* 日历网格 */}
            <div className="grid grid-cols-7 gap-2 mb-6">
              {['日', '一', '二', '三', '四', '五', '六'].map(day => (
                <div key={day} className="text-center text-sm font-medium text-gray-500 p-2">
                  {day}
                </div>
              ))}
              
              {calendarDays.map((day, index) => (
                <div
                  key={index}
                  className={`aspect-square flex items-center justify-center text-sm border rounded-lg relative ${
                    !day 
                      ? 'border-transparent' 
                      : day.isToday 
                        ? 'border-orange-500 bg-orange-50' 
                        : day.isSignedIn 
                          ? 'border-green-500 bg-green-50' 
                          : day.canMakeUp 
                            ? 'border-red-300 bg-red-50' 
                            : 'border-gray-200'
                  }`}
                >
                  {day && (
                    <>
                      <span className={`${
                        day.isToday ? 'text-orange-600 font-bold' :
                        day.isSignedIn ? 'text-green-600' :
                        day.canMakeUp ? 'text-red-500' :
                        'text-gray-700'
                      }`}>
                        {day.day}
                      </span>
                      
                      {day.isSignedIn && (
                        <span className="absolute top-1 right-1 text-green-500 text-xs">✓</span>
                      )}
                      
                      {day.canMakeUp && (
                        <span className="absolute top-1 right-1 text-red-500 text-xs">!</span>
                      )}
                    </>
                  )}
                </div>
              ))}
            </div>

            {/* 今日签到奖励 */}
            {mounted && !state.todaySignedIn && nextReward && (
              <div className="mb-4 p-4 bg-yellow-50 rounded-lg border border-yellow-200">
                <h4 className="font-semibold text-gray-800 mb-2">今日签到奖励</h4>
                <p className="text-gray-600">{nextReward.description}</p>
              </div>
            )}

            {/* 签到按钮 */}
            <button
              onClick={handleSignIn}
              disabled={!mounted || (mounted && state.todaySignedIn) || isSigningIn}
              className={`w-full py-3 px-6 rounded-lg font-bold text-white transition-all ${
                !mounted || (mounted && state.todaySignedIn)
                  ? 'bg-gray-400 cursor-not-allowed'
                  : isSigningIn
                  ? 'bg-orange-400 cursor-not-allowed'
                  : 'bg-gradient-to-r from-yellow-400 to-orange-400 hover:shadow-lg'
              }`}
            >
              {!mounted ? '加载中...' : isSigningIn ? '签到中...' : state.todaySignedIn ? '今日已签到 ✓' : '立即签到'}
            </button>
          </div>

          {/* 右侧：抽奖功能 */}
          <div className="bg-white rounded-lg p-6 shadow-sm">
            <div className="flex items-center justify-between mb-6">
              <h2 className="text-xl font-bold text-gray-800">幸运抽奖</h2>
              <div className="text-sm text-gray-600">
                剩余次数: <span className="font-bold text-purple-600">{mounted ? state.lotteryChances : 0}</span>
              </div>
            </div>

            {/* 奖品展示 */}
            <div className="grid grid-cols-2 gap-4 mb-6">
              {lotteryPrizes.slice(0, 6).map((prize) => (
                <div
                  key={prize.id}
                  className={`p-3 rounded-lg border-2 transition-all duration-300 ${
                    selectedPrize?.id === prize.id && showResult
                      ? 'border-yellow-400 bg-yellow-50 scale-105 shadow-lg'
                      : 'border-gray-200 bg-gray-50 hover:border-gray-300'
                  }`}
                >
                  <div className="text-center">
                    <div className={`w-10 h-10 mx-auto mb-2 rounded-lg bg-gradient-to-br ${prize.bgColor} flex items-center justify-center`}>
                      <span className="text-lg">
                        {prize.type === 'product' ? '📦' : prize.type === 'points' ? '💰' : '🎫'}
                      </span>
                    </div>
                    <h4 className="font-semibold text-xs text-gray-800">{prize.name}</h4>
                    <p className="text-xs text-gray-600 mt-1">{prize.description}</p>
                  </div>
                </div>
              ))}
            </div>

            {/* 抽奖按钮 */}
            <button
              onClick={handleLottery}
              disabled={!mounted || (mounted && state.lotteryChances <= 0) || isDrawing}
              className={`w-full py-3 px-6 rounded-lg font-bold text-white transition-all ${
                !mounted || (mounted && state.lotteryChances <= 0)
                  ? 'bg-gray-400 cursor-not-allowed'
                  : isDrawing
                  ? 'bg-purple-400 cursor-not-allowed animate-pulse'
                  : 'bg-gradient-to-r from-purple-500 to-pink-500 hover:shadow-lg'
              }`}
            >
              {!mounted ? (
                '加载中...'
              ) : isDrawing ? (
                '🎰 抽奖中...'
              ) : state.lotteryChances <= 0 ? (
                '暂无抽奖次数'
              ) : (
                '🎯 开始抽奖'
              )}
            </button>

            {mounted && state.lotteryChances <= 0 && (
              <p className="text-xs text-gray-500 mt-3 text-center">
                通过每日签到获得抽奖机会
              </p>
            )}

            {/* 中奖结果显示 */}
            {showResult && selectedPrize && (
              <div className="mt-4 p-4 bg-gradient-to-r from-yellow-100 to-orange-100 rounded-lg border border-yellow-200">
                <div className="text-center">
                  <div className="text-2xl mb-2">🎉</div>
                  <h3 className="text-lg font-bold text-gray-800 mb-2">恭喜中奖！</h3>
                  <div className="flex items-center justify-center space-x-3">
                    <div className={`w-10 h-10 bg-gradient-to-br ${selectedPrize.bgColor} rounded-lg flex items-center justify-center`}>
                      <span className="text-lg">🎁</span>
                    </div>
                    <div className="text-left">
                      <h4 className="font-semibold text-gray-800">{selectedPrize.name}</h4>
                      <p className="text-sm text-gray-600">{selectedPrize.description}</p>
                    </div>
                  </div>
                </div>
              </div>
            )}
          </div>
        </div>
      </div>
      <ToastContainer />
    </div>
  );
}